package com.yjt.auth.modules.user;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yjt.auth.common.bean.domain.menu.MngMenu;
import com.yjt.auth.common.bean.domain.role.MngRole;
import com.yjt.auth.common.bean.domain.user.MngUser;
import com.yjt.auth.common.constant.ConstantValues;
import com.yjt.auth.common.util.session.manager.HttpSessionManager;
import com.yjt.common.base.datasource.DBContextHolder;
import com.yjt.common.easyui.datagrid.DataGridDTO;
import com.yjt.common.easyui.datagrid.DataGridJsonDTO;
import com.yjt.common.exception.YJTException;
import com.yjt.common.model.JsonDTO;
import com.yjt.common.tools.TimeUtil;

@Controller
@RequestMapping("/auth/MngUserController")
public class MngUserController {

	private static Logger logger = LoggerFactory.getLogger(MngUserController.class);
	
	public MngUserController() {
	}
	
	@Resource(name = MngUserService.BEAN_PACKAGE_NAME)
	private MngUserService mngUserService;
	
	@RequestMapping("/doNotNeedSecurityLogin")
	@ResponseBody
	public JsonDTO doNotNeedSecurityLogin(MngUser loginUser, HttpServletRequest request) {
		JsonDTO json = new JsonDTO();
		try {
			DBContextHolder.setDBType(DBContextHolder.YJTMNG_SESSION_FACTORY);
			loginUser = mngUserService.login(loginUser);
			String projectName = request.getContextPath();
			request.getSession().setMaxInactiveInterval(60000);
			//session 设置
			request.getSession().setAttribute(ConstantValues.USER_LOGIN, loginUser);
			HttpSessionManager.addSession(request.getSession());
			json.setObj(projectName + ConstantValues.DIR_INDEX);
			json.setSuccess(true);
			json.setMsg("登录成功");
		} catch (YJTException e) {
			json.setSuccess(false);
			json.setMsg("登录失败，原因[" + e.getMessage() + "]");
		}
		return json;
	}
	
	@RequestMapping("/getUserRoleMenu")
	@ResponseBody
	public JsonDTO getUserRoleMenu(String loginUserId, HttpServletRequest request) {
		//构造左侧菜单
		MngUser loginUser = (MngUser) request.getSession().getAttribute(ConstantValues.USER_LOGIN);
		//管理员可见菜单
		MngMenu mngMenu_auth = new MngMenu("1", "权限管理模块", "0", "1", "icon-computer" ,"#", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		MngMenu mngMenu_auth_mng_user = new MngMenu("2", "用户信息管理", "1", "1", "icon-tip", "auth/MngUserController/index.do", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		//操作员可见菜单
		MngMenu mngMenu_operation = new MngMenu("3", "业务管理模块", "0", "1", "icon-user-group", "#", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		MngMenu mngMenu_operation_gcss_gddw = new MngMenu("4", "广东电网前置管理", "3", "1", "icon-user-earth", "#", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		MngMenu mngMenu_operation_gcss_gddw_ui_dkxy = new MngMenu("5", "代扣协议查询", "4", "1", "icon-user-earth", "gcss/gddw/UiDkxyController/index.do", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		MngMenu mngMenu_operation_gcss_gddw_txn_dkxy = new MngMenu("6", "用户编号映射查询", "4", "1", "icon-user-earth", "gcss/gddw/BtOrgUserNoMappingController/index.do", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		MngMenu mngMenu_operation_gcss_gddw_ui_file_log = new MngMenu("7", "批扣文件查询", "4", "1", "icon-user-earth", "gcss/gddw/UiFileLogController/index.do", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		MngMenu mngMenu_operation_gcss_gddw_ui_ssds = new MngMenu("8", "单笔代扣查询", "4", "1", "icon-user-earth", "gcss/gddw/UiSsdsController/index.do", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		MngMenu mngMenu_operation_gcss_gddw_bt_organization = new MngMenu("10", "机构信息查询", "4", "1", "icon-user-earth", "gcss/gddw/BtOrganizationController/index.do", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		MngMenu mngMenu_operation_gcss_gddw_info_sxxy = new MngMenu("11", "生效协议信息查询", "4", "1", "icon-user-earth", "gcss/gddw/InfoSxxyController/index.do", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		MngMenu mngMenu_operation_gcss_gddw_ui_plds = new MngMenu("12", "批量代收明细查询", "4", "1", "icon-user-earth", "gcss/gddw/UiPldsController/index.do", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		//MngMenu mngMenu_operation_gcss_gddw_txn_plds = new MngMenu("9", "批扣文件明细查询(标准)", "4", "1", "icon-user-earth", "gcss/gddw/TxnPldsController/index.do", TimeUtil.getCurDate("yyyyMMdd"), TimeUtil.getCurDate("HHmmss"), "index");
		
		Set<MngRole> rolesSet = new HashSet<MngRole>();
		if("YES".equalsIgnoreCase(loginUser.getAdmin())) {
			MngRole administrator = new MngRole("基础角色", "1", "业务操作员", true);
			Set<MngMenu> menusSetAdmin = new HashSet<MngMenu>();
			menusSetAdmin.add(mngMenu_auth);
			menusSetAdmin.add(mngMenu_auth_mng_user);
			administrator.setMngMenuSet(menusSetAdmin);
			rolesSet.add(administrator);
		} 
		//业务的菜单都在此添加
		MngRole operator = new MngRole("基础角色", "2", "业务操作员", true);
		Set<MngMenu> menusSetOpr = new HashSet<MngMenu>();
		menusSetOpr.add(mngMenu_operation);
		menusSetOpr.add(mngMenu_operation_gcss_gddw);
		menusSetOpr.add(mngMenu_operation_gcss_gddw_ui_dkxy);
		menusSetOpr.add(mngMenu_operation_gcss_gddw_txn_dkxy);
		menusSetOpr.add(mngMenu_operation_gcss_gddw_ui_file_log);
		menusSetOpr.add(mngMenu_operation_gcss_gddw_ui_ssds);
		menusSetOpr.add(mngMenu_operation_gcss_gddw_bt_organization);
		menusSetOpr.add(mngMenu_operation_gcss_gddw_info_sxxy);
		menusSetOpr.add(mngMenu_operation_gcss_gddw_ui_plds);
		operator.setMngMenuSet(menusSetOpr);
		rolesSet.add(operator);
		loginUser.setMngRoleSet(rolesSet);
		
		JsonDTO json = new JsonDTO();
		if(StringUtils.isNotBlank(loginUserId)) {
			json.setSuccess(true);
			json.setObj(loginUser);
		} else {
			json.setSuccess(false);
			json.setObj(request.getContextPath() + ConstantValues.DIR_LOGIN);
			json.setMsg("加载登录用户相关信息失败");
		}
		return json;
	}
	
	@RequestMapping("/index")
	public String index() {
		return "/WEB-INF/admin/auth/user/index";
	}
	
	@RequestMapping("/query")
	@ResponseBody
	public DataGridJsonDTO query(String name, HttpServletRequest request) {
		DBContextHolder.setDBType(DBContextHolder.YJTMNG_SESSION_FACTORY);
		MngUser queryModel = new MngUser();
		if(StringUtils.isNoneBlank(name)) {
			queryModel.setName(name);
		}
		return mngUserService.query(new DataGridDTO(request), queryModel);
	}
	
	@RequestMapping("/edit")
	public String edit(@RequestParam(required = true)String action, @RequestParam(required = false)String id, HttpServletRequest request) {
		DBContextHolder.setDBType(DBContextHolder.YJTMNG_SESSION_FACTORY);
		if("save".equals(action)) {
			//设置编辑页面的表单动作
			request.setAttribute(ConstantValues.ACTION,ConstantValues.ACTION_SAVE);
		}
		if("update".equals(action)) {
			request.setAttribute(ConstantValues.ACTION, ConstantValues.ACTION_UPDATE);
			MngUser mngUser = mngUserService.findById(id);
			request.setAttribute("auth_mngUser_edit", mngUser);
		}
		return "/WEB-INF/admin/auth/user/edit";
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public JsonDTO save(@ModelAttribute MngUser user) {
		DBContextHolder.setDBType(DBContextHolder.YJTMNG_SESSION_FACTORY);
		Serializable userId = mngUserService.save(user);
		JsonDTO retJson = new JsonDTO();
		if(null != userId) {
			retJson.setMsg("用户添加成功");
			retJson.setSuccess(true);
		} else {
			retJson.setMsg("用户添加失败");
			retJson.setSuccess(false);
		}
		return retJson;
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public JsonDTO update(@ModelAttribute MngUser user) {
		DBContextHolder.setDBType(DBContextHolder.YJTMNG_SESSION_FACTORY);
		boolean success = mngUserService.update(user);
		JsonDTO retJson = new JsonDTO();
		if(success) {
			retJson.setMsg("用户更新成功");
			retJson.setSuccess(true);
		} else {
			retJson.setMsg("用户更新失败");
			retJson.setSuccess(false);
		}
		return retJson;
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public JsonDTO save(@RequestParam(required = true)String[] ids) {
		DBContextHolder.setDBType(DBContextHolder.YJTMNG_SESSION_FACTORY);
		int length = (Integer) mngUserService.delete(ids);
		JsonDTO retJson = new JsonDTO();
		if(length == ids.length) {
			retJson.setMsg("用户删除成功，共删除" + length + "条数据。");
			retJson.setSuccess(true);
		} else {
			retJson.setMsg("用户删除失败");
			retJson.setSuccess(false);
		}
		return retJson;
	}
	
	/**
	 * 用户退出
	 * */
	@RequestMapping("/doNotNeedSecurityLogout")
	@ResponseBody
	public JsonDTO doNotNeedSecurityLogout(HttpServletRequest request) {
		JsonDTO retJson = new JsonDTO();
		HttpSessionManager.removeSession(request.getSession());
		request.getSession().invalidate();
		retJson.setSuccess(true);
		retJson.setObj(request.getContextPath() + ConstantValues.DIR_LOGIN);
		return retJson;
	}
}
